package com.usian.common.exception;

import com.usian.model.common.dtos.ResponseResult;
import org.apache.hbase.thirdparty.com.google.common.collect.ImmutableMap;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

@ControllerAdvice   //controller增强类  可以监听所有扫描到的controller
public class ExceptionCatch {

    // 需要一个map集合  其中  key 异常类型   value 不同的ResponseResult  线程安全 不可变的集合
    public static ImmutableMap<Class<? extends Throwable>,ResponseResult> EXCEPTIONS;
    // 构建出来的builder 对象
    public static ImmutableMap.Builder<Class<? extends Throwable>,ResponseResult> builder =  EXCEPTIONS.builder();

    static {
        builder.put(NullPointerException.class,ResponseResult.errorResult(20010,"对象不能为空！"));
        builder.put(IndexOutOfBoundsException.class,ResponseResult.errorResult(20020,"对象容量超出限制！"));
        builder.put(IOException.class,ResponseResult.errorResult(20030,"文件操作有误！"));
        builder.put(ArithmeticException.class,ResponseResult.errorResult(20040,"被除数不能为零！"));
        builder.put(ClassNotFoundException.class,ResponseResult.errorResult(20050,"对象匹配失败！"));
    }

    // modelAndView 自定义异常（可预知异常）
    @ExceptionHandler(value = {ComException.class})
    @ResponseBody
    public ResponseResult comException(ComException e){
        System.out.println(e.getMessage());
        return e.getResponseResult();
    }

    // modelAndView  不可预知异常
    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public ResponseResult exception(Exception e){
        e.printStackTrace();
        System.out.println(e.getMessage());
        // 如果有事先准备好的异常  正常提示用户
        // 如果超出范围 直接提示 99999
        // EXCEPTIONS == null 需要初始化
        if(EXCEPTIONS == null){
            // 初始化map集合
            EXCEPTIONS = builder.build();
        }
        ResponseResult responseResult =  EXCEPTIONS.get(e.getClass());
        if(responseResult != null){
            return responseResult;
        }
        // 提示99999
        return ResponseResult.errorResult(99999,"出现未知问题，请联系管理员！");
    }




}
